package com.example.commonlib.base.view;


import com.example.commonlib.ResourceTable;
import com.example.commonlib.base.components.StateChangedListenerAdapter;
import ohos.aafwk.ability.AbilitySlice;
import ohos.agp.animation.Animator;
import ohos.agp.animation.AnimatorProperty;
import ohos.agp.components.*;
import ohos.agp.components.element.Element;
import ohos.agp.window.dialog.ToastDialog;
import ohos.agp.window.service.Display;
import ohos.agp.window.service.DisplayAttributes;
import ohos.agp.window.service.DisplayManager;
import ohos.hiviewdfx.HiLog;
import ohos.hiviewdfx.HiLogLabel;

import java.util.Optional;

/**
 *  Activity 顶级父类 : 添加各种状态 ( 数据错误，数据为空，数据加载中 ) 页的展示，
 * 自定义的 MaterialDialog 的显示，进度条 dialog 显示
 * @author linlongxin 2018/3/27.
 */
public abstract class BaseAbility extends AbilitySlice implements ISuperFunction {
    private final HiLogLabel tag = new HiLogLabel(HiLog.LOG_APP,0x00201, BaseAbility.class.getSimpleName());
    private static final int ANIMATION_DURATION = 300;
    protected boolean isUseStatusPages = false;
    private boolean isShowLoading = true;
    private boolean isShowingContent = false;
    private boolean isShowingError = false;
    private boolean isShowingEmpty = false;
    private final int NUM= 16;
    private final int NUM_400= 400;
    private final float NUM_0= 0.5f;
    private AnimatorProperty mShowAnimator;
    private AnimatorProperty mHideAnimator;
    // status page
    protected DirectionalLayout mEmptyPage;
    protected DirectionalLayout mErrorPage;
    protected DirectionalLayout mLoadingPage;
    protected Component mRealContent;
    // 当前显示的 page
    protected Component mCurrentPage;
    protected DirectionalLayout mLoadDataButton;
    private ToastDialog mLoadingDialog;
/*
* */
    @Override
    public void setUIContent(ComponentContainer layoutResID) {
        if (isUseStatusPages) {
            onInitPages(layoutResID.getId());
        } else {
            super.setUIContent(layoutResID.getId());
        }
    }

    protected void setTitleBarContentView(ComponentContainer layoutResID) {
        super.setUIContent(layoutResID);
    }

    @Override
    public void onInitPages(int contentId) {
        ComponentContainer stackLayout = (ComponentContainer) LayoutScatter.getInstance(getContext()).parse(ResourceTable.Layout_ability_main, null, false);
        Component root = LayoutScatter.getInstance(this).parse(ResourceTable.Layout_base_status_page, stackLayout, false);
        // 把 activity 要显示的 xml 加载到 mContent 布局里
        mRealContent = LayoutScatter.getInstance(this).parse(contentId, null, false);
        if (root instanceof StackLayout) {
            ((StackLayout) root).addComponent(mRealContent);
        }
        stackLayout.addComponent(root);
        mEmptyPage = (DirectionalLayout) stackLayout.findComponentById(ResourceTable.Id_empty_page);
        mLoadDataButton = (DirectionalLayout) stackLayout.findComponentById(ResourceTable.Id_error_to_load_button);
        mErrorPage = (DirectionalLayout) stackLayout.findComponentById(ResourceTable.Id_error_page);
        mLoadingPage = (DirectionalLayout) stackLayout.findComponentById(ResourceTable.Id_loading_page);


        mRealContent.setVisibility(Component.FOCUS_ENABLE);
        mCurrentPage = mLoadingPage;
        showError();

        mLoadDataButton.setClickedListener(new Component.ClickedListener() {
            @Override
            public void onClick(Component component) {
                onErrorRetry(component);
            }
        });
    }

    @Override
    public void onInitPages(LayoutScatter inflater, int contentId) {

    }


    @Override
    public Component findComponentById(int resID) {
        if (isUseStatusPages) {
            return mRealContent.findComponentById(resID);
        } else {
            return super.findComponentById(resID);
        }
    }

    /**
     * 是否开启状态页
     * @param show
     */
    public void setStatusPageEnable(boolean show) {
        isUseStatusPages = show;
    }


    @Override
    public void showEmpty() {

        HiLog.debug(tag,"showEmpty");

        if (!isShowingEmpty) {
            showView(mEmptyPage);
            isShowingError = false;
            isShowingContent = false;
            isShowLoading = false;
            isShowingEmpty = true;
        }
    }

    @Override
    public void showError() {

        HiLog.debug(tag,"showError");

        if (!isShowingError) {
            showView(mErrorPage);
            isShowingError = true;
            isShowingContent = false;
            isShowLoading = false;
            isShowingEmpty = false;
        }
    }

    @Override
    public void showLoading() {

        HiLog.debug(tag,"showLoading");

        if (!isShowLoading) {
            showView(mLoadingPage);
            isShowingError = false;
            isShowingContent = false;
            isShowLoading = true;
            isShowingEmpty = false;
        }
    }

    @Override
    public void showContent() {

        HiLog.debug(tag,"showContent");

        if (!isShowingContent) {
            showView(mRealContent);
            isShowingContent = true;
            isShowingError = false;
            isShowLoading = false;
            isShowingEmpty = false;
        }
    }


    @Override
    public void onErrorRetry(Component v) {
        showLoading();
    }

    private void showView(Component view) {
        hideViewWithAnimation(mCurrentPage);
        mCurrentPage = view;
        showViewWithAnimation(view);
    }

    /**
     * 展示状态页添加动画
     *
     * @param view
     */
    private void showViewWithAnimation(final Component view) {
        if (mShowAnimator != null) {
            mShowAnimator.cancel();
        }
        view.setVisibility(Component.VISIBLE);
        view.setAlpha(0f);
        mShowAnimator = view.createAnimatorProperty().alpha(1).setDuration(ANIMATION_DURATION);
        mShowAnimator.start();
    }

    /**
     * 隐藏状态页添加动画
     *
     * @param view
     */
    private void hideViewWithAnimation(final Component view) {
        if (mHideAnimator != null) {
            mHideAnimator.setStateChangedListener(null);
            mHideAnimator.cancel();
        }
        view.setAlpha(1f);
        mHideAnimator = view.createAnimatorProperty()
                .alpha(0f)
                .setDuration(NUM_400);
        mHideAnimator.start();
        mHideAnimator.setStateChangedListener(new StateChangedListenerAdapter() {
            @Override
            public void onStop(Animator animator) {
                super.onStop(animator);
                view.setVisibility(Component.FOCUS_ENABLE);
            }
        });
    }

    /**
     * 显示进度条的dialog
     */
    @Override
    public void showLoadingDialog() {
        if (mLoadingDialog == null) {
            ProgressBar progressBar = new ProgressBar(this);
            progressBar.setPadding(dp2px(NUM), dp2px(NUM), dp2px(NUM), dp2px(NUM));
            Element element = new Element() {
                @Override
                public void setAlpha(int alpha) {
                    super.setAlpha(0);
                }
            };
            progressBar.setProgressBackgroundElement(element);
            mLoadingDialog = new ToastDialog(this)
                    .setComponent(progressBar);
        }
        mLoadingDialog.show();
    }

    @Override
    public void dismissLoadingDialog() {
        if (mLoadingDialog != null) {
            mLoadingDialog.destroy();
            mLoadingDialog = null;
        }
    }

    public int dp2px(float dpValue) {
        // 获取屏幕密度
        Optional<Display> display = DisplayManager.getInstance().getDefaultDisplay(this.getContext());
        DisplayAttributes displayAttributes = display.get().getAttributes();
        final float scale = displayAttributes.densityPixels;
        return (int) (dpValue * scale + NUM_0);
    }

    @Override
    protected void onStop() {
        super.onStop();
        if (mShowAnimator != null) {
            mShowAnimator.cancel();
        }
        if (mHideAnimator != null) {
            mHideAnimator.cancel();
        }
    }
}
